﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MonoTouchAutoBind
{
    static class BindBlock
    {

        private static string patternStart = @"(?'returnType'\w+)\s*\(\s*\^\s*(?'delegateType'\w+)?\s*\)\s*\(\s*(?'params'[*\s\w,]*)\s*\)" ;//"void\s*\(\s*\^\s*\)\s*\(\s*(?'params'[*\s\w,]*)\s*\)";
        private static System.Text.RegularExpressions.Regex regex = null;

        static BindBlock()
        {
            regex = new System.Text.RegularExpressions.Regex(patternStart);
        }

        public static bool CanParse(string code)
        {
            return regex.IsMatch(code);
        }

        public static bool GenerateCSharp(string delegateName, string parseCode, out string deleteCode)
        {
            deleteCode = "";
            if (!regex.IsMatch(parseCode))
                return false;

            Match match= regex.Match(parseCode);
            string codeParams= match.Groups["params"].Value.Trim();

            string[] mc = codeParams.Split(new char[] { ',' });

            List<paramTypeName> list = new List<paramTypeName>();
            foreach (var ma in mc)
            {
                if (ma.Trim().Length == 0)
                    continue;
                var newma = ma.Trim();
                paramTypeName p = new paramTypeName()
                {
                    paramType = newma.Substring(0, newma.IndexOf(" ") ).Replace("*", ""),
                    paramName = newma.Substring(newma.LastIndexOf(" ") + 1).Replace("*", "")
                };
                list.Add(p);
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("delegate void {0} (", delegateName);

            //delegate void SetDrawerVisualStateBlockCallback (MMDrawerController  drawerController, MMDrawerSide drawerSide, float percentVisible);
            for (int i = 0; i < list.Count; i++)
            {
                sb.AppendFormat("{0}{1} {2}", i == 0 ? "" : ",", list[i].paramType, list[i].paramName);
            }
            sb.AppendFormat(");");
            deleteCode = sb.ToString();
            return true;
        }

        class paramTypeName
        {
            public string paramName { get; set; }
            public string paramType { get; set; }
        }

    }
}
